package com.sniper.springmvc.action.admin;

import com.sniper.springmvc.action.RootController;
import com.sniper.springmvc.cache.CacheTemplateService;
import com.sniper.springmvc.model.AdminRight;
import com.sniper.springmvc.model.AdminUser;
import com.sniper.springmvc.mybatis.service.BaseService;
import com.sniper.springmvc.mybatis.service.impl.AdminRightService;
import com.sniper.springmvc.mybatis.service.impl.AdminUserService;
import com.sniper.springmvc.mybatis.service.impl.CollectService;
import com.sniper.springmvc.utils.HttpRequestUtils;
import com.sniper.springmvc.utils.TreeZTreeUtil;
import com.sniper.springmvc.utils.UserDetailsUtils;
import com.sniper.springmvc.utils.ValidateUtil;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import javax.annotation.Resource;
import java.util.*;

public abstract class AdminBaseController extends RootController {


    @Resource
    AdminRightService adminRightService;

    @Resource
    AdminUserService adminUserService;

    @Resource
    CollectService collectService;


    @Resource
    CacheTemplateService cacheTemplateService;

    /**
     * 系统左侧菜单使用 组装ztree必备
     */
    private static List<AdminRight> zTreeMenuData = new ArrayList<>();

    /**
     * 用静态方法储存
     *
     * @return
     */
    List<AdminRight> getzTreeMenuData() {

        if (zTreeMenuData.size() == 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("theMenu", true);
            params.put("type", "admin");
            params.put("order", "sort asc");
            zTreeMenuData = adminRightService.query("select", params);
        }
        return zTreeMenuData;
    }

    public AdminBaseController() {
        super();
    }

    @Override
    @ModelAttribute
    public void init(Map<String, Object> map) {
        // ajax不需要获取下面数据
        // 先执行前边的
        super.init(map);
        if (HttpRequestUtils.isAjax(request)) {
            return;
        }

        String url = this.request.getRequestURI().replaceFirst(this.request.getContextPath(), "");
        // 去除jsessionid，用于和后台地址比对
        if (url.contains(";")) {
            url = url.substring(0, url.indexOf(";"));
        }
        baseHref.setUrl(url);
        // 组装左边菜单
        TreeZTreeUtil treeUtil = new TreeZTreeUtil();
        UserDetailsUtils detailsUtils = new UserDetailsUtils();
        // 下面是导航数据处理
        treeUtil.setUrlPath(url);
        treeUtil.setAdminPath(adminPath);
        treeUtil.setAdminRights(getzTreeMenuData());
        if (detailsUtils.getAdminUser() != null) {
            treeUtil.setAdminGroups(detailsUtils.getAdminUser().getAdminGroup());
        }
        treeUtil.checkAdminPath();
        treeUtil.init();

        // 增加栏目式的新闻链接
        map.put("menuTop", treeUtil.getMenuTop());
        map.put("menuSub", treeUtil.getMenuSub());
        map.put("menuThree", treeUtil.getMenuThree());

        // 检测是否是新闻添加也面
        // 获取当前url的实体
        AdminRight adminRight = treeUtil.getRightByUrl();
        if (null != adminRight) {
            baseHref.setMenuId(adminRight.getId());
            baseHref.setPageTitle(adminRight.getName());

            List<String> title = new ArrayList<>();
            title.add(adminRight.getName());
            getMenuBar(adminRight.getFid(), title);
            Collections.reverse(title);
            baseHref.setMenuBar(title);
        }
    }


    /**
     * 获取导航数据
     *
     * @return
     */
    private String getMenuBar(String fid, List<String> title) {
        // 通过一个for循环读取adminRight的层级关系
        while (true) {
            if (ValidateUtil.isValid(fid)
                    && !fid.equals(TreeZTreeUtil.menuTopId)) {
                AdminRight adminRight2 = null;
                for (AdminRight adminRight : getzTreeMenuData()) {
                    if (fid.equals(adminRight.getId())) {
                        adminRight2 = adminRight;
                        break;
                    }
                }
                if (adminRight2 != null) {
                    title.add(adminRight2.getName());
                    return getMenuBar(adminRight2.getFid(), title);
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        return "";
    }

    /**
     * 获取用户id用于和其他表关联
     *
     * @return
     */
    public AdminUser getAdminUser() {
        UserDetailsUtils detailsUtils = new UserDetailsUtils();
        return detailsUtils.getAdminUser();
    }

    @Override
    protected String redirect(String dir) {
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX + adminPath + dir;
    }

    @Override
    protected String forward(String dir) {
        StringBuilder builder = new StringBuilder();
        builder.append(site.getName());
        if (!dir.startsWith("/")) {
            builder.append("/");
        }
        builder.append(dir);
        return builder.toString();
    }


    /**
     * 删除
     *
     * @param ajaxResult
     * @param services
     * @param delid
     */
    public void delete(Map<String, Object> ajaxResult, BaseService services, String[] delid) {
        try {
            for (String string : delid) {
                services.delete(string);
            }
            ajaxResult.put("code", 1);
            ajaxResult.put("msg", "success");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", -1);
            ajaxResult.put("msg", "删除失败");
        }

    }

}